import { defineStore } from "pinia";
import {RouterState} from "@/interface";
import { errorRouter, staticRouter } from "@/routers/modules/staticRouter";
import {RouteRecordRaw} from "vue-router";

// DynamicRouterStore
export const routerStore = defineStore({
    id: "qiyi183-blog-router",
    state: (): RouterState => ({
        // 当前页面的 router id，用来做按钮权限筛选
        routeId: "",
        // 当前页面的 router name，用来做按钮权限筛选
        routeName: "",
        // 是否已初始化动态路由
        dynamicRouteInit: false,
        // 路由列表
        routers: [...staticRouter, ...errorRouter],
        // 新增路由列表
        dynamicRouters: [],
        // keepAliveComponents
        keepAliveNames: []
    }),
    getters: {
        getRouteName: state => state.routeName,
        // 获取是否初始化动态路由
        getDynamicRouteInit: state => state.dynamicRouteInit
    },
    actions: {
        // setRouteId
        setRouteId(id: string) {
            this.routeId = id;
        },
        // setRouteName
        setRouteName(name: string) {
            this.routeName = name;
        },
        // setKeepAliveNames
        setKeepAliveNames(keepAliveNames: string[]) {
            this.keepAliveNames = keepAliveNames;
        },
        removeKeepAliveName(keepAliveName: string) {
            const index = this.keepAliveNames.indexOf(keepAliveName);
            this.keepAliveNames.splice(index, 1);
        },
        addKeepAliveName(keepAliveName: string) {
            if (!this.keepAliveNames.includes(keepAliveName)) {
                this.keepAliveNames.push(keepAliveName);
            }
        },
        addDynamicRouter(router: RouteRecordRaw) {
            this.dynamicRouters.push(router);
        },
        // resetRouters
        resetRouters() {
            this.routeName = "";
            this.keepAliveNames = [];
            this.dynamicRouters = [];
            this.dynamicRouteInit = false;
            this.routers = [...staticRouter, ...errorRouter];
        },
        // Set dynamicRouteInit
        setDynamicRouterInit(init: boolean) {
            this.dynamicRouteInit = init;
        }
    }
});
